package com.shxzz.easy12306.framework.starter.base.init;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 应用就绪后处理器，发布一次性事件
 * @author shxzz
 * @create 2024-02-20-20:26
 */
public class ApplicationReadyPostProcessor {

    private ApplicationContext applicationContext;

    /**
     * 事件发布标识，确保 {@link ApplicationInitializingEvent} 事件只发布一次
     */
    private AtomicBoolean executeFlag = new AtomicBoolean(false);

    public ApplicationReadyPostProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void publishOnceEvent(ApplicationReadyEvent event) {
        if(!executeFlag.compareAndSet(false, true)) {
            return;
        }
        applicationContext.publishEvent(new ApplicationInitializingEvent(this));
    }
}
